import md5 from 'md5';
import moment from 'moment';
import LineIcon from '@/assets/images/linepay.png';
import Applepay from '@/assets/images/applepay.png';
import Creditpay from '@/assets/images/creditpay.png';
import Alipay from '@/assets/images/alipay.png';
import WechatPay from '@/assets/images/wechatpay.png';
import CashPay from '@/assets/images/cash.png';
import {picPath} from '@/config'

declare var window: any ;

/**
 * 获取随机占位图
 *
 * @param {number} w 宽
 * @param {number} h 高
 * @return {*} https://unsplash.it/${w}/${h}?v=${Math.random()}
 */
export function getMockPic(w: number, h: number) {
  return `http://lorempixel.com/${w}/${h}/food?v=${Math.random()}`;
}

/**
 * 为空判断
 *
 * @param {*} value
 * @return {*}  {boolean}
 */
export function isEmpty(value: any): boolean {
  switch (typeof value) {
    case 'undefined':
      return true;
    case 'string':
      return (
        value === '' ||
        value === undefined ||
        value === null ||
        value === 'undefined' ||
        value === 'null'
      );
    case 'object': {
      if (value instanceof Array) return value.length < 1;
      else if (value instanceof Date) return false;
      else if (value instanceof Object) return Object.keys(value).length < 1;
      else return true;
    }
    default:
      return false;
  }
}

/**
 * 打电话
 *
 * @param {string} num 电话号码
 * @return {*}
 */
export function callPhone(num: string): boolean {
  let merge = /^\d{8,16}$/;
  if (merge.test(num)) {
    let oA = document.createElement('a');
    oA.href = `tel:${num}`;
    oA.click();
    return true;
  } else {
    return false;
  }
}

/**
 * 防抖
 * - 阻断前面的执行，仅执行最后一次
 * @param {Function} fn 需执行的函数
 * @param {number} wait 等待的时间
 * @return {*}  {Function}
 */
export function debounce(fn: Function, wait: number): Function {
  let timer: NodeJS.Timeout | null = null;
  return function(this: any) {
    let context = this;
    let args = arguments;
    if (timer) {
      clearTimeout(timer);
      timer = null;
    }
    timer = setTimeout(function() {
      fn.apply(context, args);
    }, wait);
  };
}

/**
 * 防抖
 * - 阻断后面的执行，仅执行第一次
 * @param {Function} fn 需执行的函数
 * @param {number} wait 等待的时间
 * @return {*}  {Function}
 */
export function debounceAfter(fn: Function, wait: number): Function {
  let timer: NodeJS.Timeout | null = null;
  return function(this: any) {
    let context = this;
    let args = arguments;

    if (timer) clearTimeout(timer);

    let callNow = !timer;
    timer = setTimeout(() => {
      timer = null;
    }, wait);

    if (callNow) fn.apply(context, args);
  };
}

/**
 * @desc 函数节流
 * @param func 函数
 * @param wait 延迟执行毫秒数
 * @param type 1 表时间戳版，2 表定时器版
 */
export function throttle(func: Function, wait: number, type: number): Function {
  let previous = 0;
  let timeout: NodeJS.Timeout | null = null;
  return function(this: any) {
    let context = this;
    let args = arguments;
    if (type === 1) {
      let now = Date.now();

      if (now - previous > wait) {
        func.apply(context, args);
        previous = now;
      }
    } else if (type === 2) {
      if (!timeout) {
        timeout = setTimeout(() => {
          timeout = null;
          func.apply(context, args);
        }, wait);
      }
    }
  };
}
/**
 * 震动手机
 *
 * @param {(number | number[])} pattern 震动、暂停间隔的模式
 */
export function shakeIt(pattern: number | number[]) {
  if (navigator && navigator.vibrate) {
    navigator.vibrate(pattern);
  }
}

// 展开数组
export function flatten(arr: any[]){
  let result:any=[]
  for(let i=0,l=arr.length;i<l;i++){
      if(Array.isArray(arr[i])){
          //递归调用
          result=result.concat(flatten(arr[i]))  
      }else{
          result.push(arr[i])
      }
  }
  return result
}


/* 获取图片全路径
  [name] 名称，
  [size] 图片大小，300/600
*/
export const getUmePic = (name:any, size = 300) => {
  if (isEmpty(name)) return undefined;
  if (name.indexOf('http') > -1) {
    // return `${name}`;
    return `${name}/${size}`;
  } else {
    return `${picPath}/public/service/showImage?filename=${name}`;
  }
}

/* 判断是否显示支付按钮 */
export const showPayButton = () => {
  return window.ApplePaySession && window.ApplePaySession.canMakePayments;
}

export const payIcon = (way:string) => {
  let pays = new Map([[ 'linepay', LineIcon], ['applepay', Applepay], ['cardpay', Creditpay], ['alipay', Alipay], ['fbwechat', WechatPay], ['cashpay', CashPay]])
  return pays.get(way)
}

/* 字段判斷 */
export const checkField = (rule:any, value:any) => {
  let msg = '';
  switch (rule) {
    case 'phone': {
      if (!(/^\d{8,11}$/.test(value)
      )) {
        msg = '請輸入符合格式的手機號碼';
      } break;
    };
    case 'phone_86': {
      if (!(/^1(3[0-9]|4[57]|5[0-35-9]|7[0135678]|8[0-9]|9[0-9])\d{8}$/.test(value))) {
        msg = '請輸入正確的大陸手機號';
      } break;
    };
    case 'phone_886': {
      if (!(/^09\d{8}$/.test(value))) {
        msg = '請輸入正確的台灣手機號';
      } break;
    };
    case 'phone_852': {
      if (!(/^\d+$/.test(value))) {
        msg = '請輸入正確的香港手機號';
      } break;
    };
    case 'password': {
      if (!(/^[0-9A-Za-z]{6,16}$/.test(value))) {
        msg = '請輸入符合格式的密碼'
      } break;
    };
    case 'captcha': {
      if (!(/^\d{4,6}$/.test(value))) msg = '請輸入符合格式的驗證碼'; break;
    };
    case 'card': {
      if (!(/^\d{16,20}$/.test(value))) msg = '信用卡號為16至20位數字'; break;
    };
    case 'CVC': {
      if (!(/^\d{3}$/.test(value))) msg = '安全碼為3位數字'; break;
    };
    case 'month': {
      if (!(/^0?[1-9]$|^1[0-2]$/.test(value))) msg = '月份格式不正確'; break;
    };
    case 'year': {
      if (!(/^\d{2}$/.test(value))) msg = '年份格式不正確'; break;
    };
    case 'email': {
      if (!(/^.+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/.test(value))) msg = '郵箱格式不正確'; break;
    };
    default: msg = '';
  }
  if (isEmpty(value) && isEmpty(msg)) msg = '請檢查數據是否符合規則';
  return msg;
}

/** md5加密 */
export function encryptMd5(password: any): string {
  return md5(password).toLowerCase();
}

/** 操作localstorage數據 */
export const JsonStorge = {
  set: (name: string, data: any) => { localStorage.setItem(name, JSON.stringify(data)) },
  get: (name: string) => JSON.parse(localStorage.getItem(name) || '{}'),
  copy: (data: any) => JSON.parse(JSON.stringify(data))
}
/**
 * 等待
 *
 * @param {number} sec 秒s
 * @return {*} 返回 promise
 */
export function waitBy(sec: number): Promise<any> {
  let timed: any = undefined;
  return new Promise(resolve => {
    clearTimeout(timed);
    timed = setTimeout(() => {
      resolve();
      clearTimeout(timed);
    }, sec * 1000);
  });
}


export const payWayName = new Map([['cashpay', '現金支付'], ['applepay', 'Apple Pay'], ['alipay', '支付寶'], ['linepay', 'Line Pay'], ['fbwechat', '微信支付'], ['cardpay', '信用卡支付']]);


/* 時間格式化 */
export const dateFormat = (date:any, type:any) => {
  if (typeof date === 'string' && date.indexOf('-') > -1) {
    date = date.replace(/\-/g, "/");
  }
  const zero = (num:number) => num < 10 ? `0${num}` : num;
  const newDt = new Date(date);
  const dy = newDt.getFullYear();
  const dm = zero(newDt.getMonth() + 1);
  const dd = zero(newDt.getDate());
  const th = zero(newDt.getHours());
  const tm = zero(newDt.getMinutes());
  const ts = zero(newDt.getSeconds());
  switch (type) {
    case 'YYYY-MM': return `${dy}-${dm}`;
    case 'YYYY-MM-DD': return `${dy}-${dm}-${dd}`;
    case 'YYYY-MM-DD hh:mm': return `${dy}-${dm}-${dd} ${th}:${tm}`;
    case 'YYYY-MM-DD hh:mm:ss': return `${dy}-${dm}-${dd} ${th}:${tm}:${ts}`;
    case 'hh:mm': return `${th}:${tm}`;
    case 'hh:mm:ss': return `${th}:${tm}:${ts}`;
    default: return `${dy}-${dm}-${dd} ${th}:${tm}:${ts}`;
  }
}

export const getCookie = (cname:string) =>{
  var name = cname + "=";
  var ca = document.cookie.split(';');
  for(var i=0; i<ca.length; i++) 
  {
    var c = ca[i].trim();
    if (c.indexOf(name)==0) return c.substring(name.length,c.length);
  }
  return "";
}

// 是否在umeApp打開
export const isOpenInUmeApp = () => {
  // return getCookie('user_platform') === 'umeApp' 
  return window.umeApp && window.umeApp.getUserPlatform() === 'umeApp';
}

/* 获取请求头 */
export const getServiceHeaders = () => {
  const {
    token = undefined,
    userId = undefined,
  } = JSON.parse(localStorage.getItem('userInfo') || '{}') || {};
  // console.log()
  return {
    'Content-Type': 'application/json',
    'Token': token,
    'Buy-Flag': !isEmpty(localStorage.getItem("userInfo") )? 'umeMember' : 'trendlabstore.cn' ,//登录的情况下传umemember否则就传trendlabstore.cn
    'Request-Tk': token || undefined,
    'merId': '',
    'Platform': 'web',
    'braId': localStorage.getItem("BRAID"),
    'Bra-Id': localStorage.getItem("BRAID"),
  }
}

export const storeOptionListMap = (storeOptionList:any) => {
  const newStoreOptionList = JSON.parse(JSON.stringify(storeOptionList))
  let map = new Map();
  if (!isEmpty(newStoreOptionList)) {
    newStoreOptionList.forEach((item: any) => {
      map.set(item.optionType, item.optionValue)
    })
  }
  return map
}

// 预订时间距离现在大概多久
export const timeLeft = (preEndTime:any) => {
  let time = moment(`${moment().format('YYYY-MM-DD')} ${preEndTime}`).format('YYYY-MM-DD HH:mm:ss');
  let currentTime = moment().format('YYYY-MM-DD HH:mm:ss');
  let leftms = moment(time).valueOf() - moment(currentTime).valueOf();
  let hours = parseInt((leftms / 1000 / 60 / 60).toString());
  leftms = leftms - hours * 60 * 60 * 1000;
  let minutes = parseInt((leftms / 1000 / 60).toString());
  if(leftms > 0 && (padLeft0(hours) !== '00' || padLeft0(minutes) !== '00')) {
    return `${padLeft0(hours) !== '00' ? `${padLeft0(hours)}小時` : ''}${padLeft0(minutes)}分鐘後`
  }
}

const padLeft0  = (number:any) => {
  return `0${number}`.slice(-2)
}

